package com.ocelot.san.converter;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;

import com.ocelot.san.dto.Role;
import com.ocelot.san.service.RoleService;

@ManagedBean 
@RequestScoped 
public class RoleConverter implements Converter {

  	@ManagedProperty("#{roleService}")
    private RoleService roleService;
 
    public Object getAsObject(FacesContext context, UIComponent component, String value) { 
        try {
        	Long id = Long.valueOf(value);
        	return roleService.findById(id);
        } catch (Exception e) { 
            throw new ConverterException(new FacesMessage(String.format("Cannot convert %s to Role", value)), e); 
        } 
    }
    
    public String getAsString(FacesContext context, UIComponent component, Object value) {
    	if(value!=null) {
	    	if(value instanceof Role) {
	    		Role role = (Role) value;
	            return String.valueOf(role.getId()); 
	    	}
    		return value.toString();
    	}
    	return null;
    }


	public RoleService getRoleService() {
		return roleService;
	}


	public void setRoleService(RoleService roleService) {
		this.roleService = roleService;
	}
 
}

 
 
